<?php

namespace App\Company\Controllers;

use App\Company\Repositories\Jobposition;
use App\Models\JobpositionModel;
use App\Models\JobPositionUpdateModel;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Http\Controllers\AdminController;
use Dcat\Admin\Widgets\Table;
use SuperEggs\DcatDistpicker\DcatDistpickerHelper;
use Dcat\Admin\Widgets\Alert;
use Dcat\Admin\Widgets\Modal;
use Dcat\Admin\Grid\Displayers\Select;

class JobpositionController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new Jobposition(['company', 'categories', 'checkInfo']), function (Grid $grid) {
            $grid->model()->orderByDesc('id');
            $grid->column('created_at', '发布时间')->sortable();
            $grid->column('position_name');
            $grid->column('region')->display(function () {
                if (!$this->region_region) {
                    return '全国';
                }
                return DcatDistpickerHelper::getAreaName($this->region_province) . DcatDistpickerHelper::getAreaName($this->region_city) . DcatDistpickerHelper::getAreaName($this->region_region);
            });
            $status = [JobpositionModel::STATUS_ON_LINE => '上架', JobpositionModel::STATUS_OFF_LINE => '下架'];
            //            unset($status[JobpositionModel::STATUS_CHECK_AWAIT],$status['JobpositionModel::STATUS_AWAIT_REJECT']);
            //            $grid->column('cur_status','上架状态')->select($status);
            $status = [JobpositionModel::STATUS_ON_LINE => '上架', JobpositionModel::STATUS_OFF_LINE => '下架'];

            $grid->column('cur_status')->display(function ($cur_status) {
                if ($cur_status == JobpositionModel::STATUS_AWAIT_REJECT) {
                    $opinion = $this->checkInfo->opinion ?? '';
                    $res = '';
                    if ($opinion) {
                        $body =  "<div  style='padding:10px 10px 0;white-space: pre'>$opinion</div>";
                        $res = Modal::make()
                            ->lg()
                            ->title('审核意见')
                            ->body($body)
                            ->button('查看原因');
                    }
                    return '已驳回' . $res;
                } else {
                    $col = [
                        1 => '#266EFF',
                        2 => '#1B1F26',
                        3 => '#FF6600',
                    ][$cur_status];
                    return '<span class="label" style="background:' . $col . '">' . JobpositionModel::STATUS_LIST[$cur_status] . '</span>';
                }
            });
            $grid->column('updated_at')->sortable();
            $grid->column('statistics.pv', '浏览量')->display(function ($value) {
                return $value ?? 0;
            });
            $grid->column('statistics.uv', '浏览人数')->display(function ($value) {
                return $value ?? 0;
            });
            $grid->column('recruit_num', '报名人数');
            $grid->column('content', '联系方式')
                ->display('查看') // 设置按钮名称
                ->modal(function ($modal) {
                    // 设置弹窗标题
                    $modal->title('联系方式');

                    // 自定义图标
                    $modal->icon('feather icon-aperture');
                    //                    return "<div style='padding:10px 10px 0'>暂无联系方式</div>";
                    $card = new Table();
                    $rows = [];
                    $header = [];
                    if ($this->contact_type == JobpositionModel::CONTACT_MOBILE) {
                        $header = ['手机号', '最大报名人数人数', '报名人数'];
                        foreach ($this->contactPhone as $item) {
                            $rows[] = [
                                $item->phone_number,
                                $item->number,
                                $item->recruit_num,
                            ];
                        }
                    }
                    if ($this->contact_type == JobpositionModel::CONTACT_QQ) {
                        $header = ['QQ号码', '二维码', '最大报名人数人数', '报名人数'];
                        foreach ($this->contactQq as $item) {
                            $rows[] = [
                                $item->qq_number,
                                "<image src='$item->qq_qr_code' style='width: 150px'>",
                                $item->number,
                                $item->recruit_num,
                            ];
                        }
                    }
                    if ($this->contact_type == JobpositionModel::CONTACT_WECHAT) {
                        $header = ['微信号', '二维码', '最大报名人数人数', '报名人数'];
                        foreach ($this->contactWechat as $item) {
                            $rows[] = [
                                $item->wechat_number,
                                "<image src='$item->wechat_qr_code' style='width: 150px'>",
                                $item->number,
                                $item->recruit_num,
                            ];
                        }
                    }
                    if ($this->contact_type == JobpositionModel::CONTACT_DINGTALK) {
                        $header = ['钉钉号', '二维码', '最大报名人数人数', '报名人数'];
                        foreach ($this->contactDingtalk as $item) {
                            $rows[] = [
                                $item->dingtalk_number,
                                "<image src='$item->dingtalk_qr_code' style='width: 150px'>",
                                $item->number,
                                $item->recruit_num,
                            ];
                        }
                    }
                    if ($header) {
                        $card->setHeaders($header)->setRows($rows);
                        return "<div style='padding:10px 10px 0'>$card</div>";
                    } else {
                        return "<div style='padding:10px 10px 0'>暂无联系方式</div>";
                    }
                });
            $grid->column('selection_date_start');
            $grid->column('selection_date_end');
            $grid->column('work_time_start');
            $grid->column('work_time_end');
            $grid->column('updated_at')->sortable();

            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $url = admin_url("sign-up?job_position_id=$this->id");
                $actions->append("<a href='" . $url . "' class='btn btn-success btn-sm'>报名列表</a>");
            });
            
            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $url = admin_url("chat?job_position_id=$this->id");
                $actions->append("<a href='{$url}' class='btn btn-sm' style='margin-left:10px;'>客服</a>");
            });

            $grid->selector(function (Grid\Tools\Selector $selector) {
                $list = JobpositionModel::STATUS_LIST;
                $selector->selectOne('cur_sss', '状态', $list, function ($query, $value) {
                    $query->where('cur_status', $value);
                });
            });


            $grid->filter(function (Grid\Filter $filter) {
                $filter->expand();
                $filter->panel();
                $filter->like('position_name')->width(2);
            });
            $grid->fixColumns(0, -1);
            // 禁用过滤器按钮
            $grid->disableFilterButton();
            //边框模式
            //            $grid->withBorder();
            //横向滚动条
            $grid->scrollbarX();
            // 禁用批量删除按钮
            $grid->disableBatchDelete();
            // 禁用显示按钮
            $grid->disableViewButton();
            $grid->disableRowSelector();
            $grid->disableDeleteButton();
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new Jobposition(['contactPhone', 'contactQq', 'contactWechat']), function (Form $form) {
            // 第一列占据1/2的页面宽度

            $info = '<i class="fa fa-exclamation-circle"></i> 补充职位信息，求职者精准度';
            $form->html(Alert::make($info)->info());
            $form->text('position_name')->help('修改后需要审核才能生效')->required();
            $form->text('salary')->required()->help('修改后需要审核才能生效');
            $form->select('salary_type')->options(JobpositionModel::SALARY_TYPE_LIST)->required()->help('修改后需要审核才能生效');
            $form->distpickerNationwide(['region_province', 'region_city', 'region_region'], '招聘区域')->autoselect(0)->help('修改后需要审核才能生效');
            $form->textarea('job_description')->rows(4)->required()->help('修改后需要审核才能生效');
            $info = '<i class="fa fa-exclamation-circle"></i> 岗位[已在架]时才生效';
            $form->html(Alert::make($info)->info());
            $form->timeRangeC('selection_date_start', 'selection_date_end', '招聘日期')->options([
                'format' => 'YYYY-MM-DD',
            ]);
            $form->timeRangeC('work_time_start', 'work_time_end', '招聘时段');

            $info = '<i class="fa fa-exclamation-circle"></i> 请设置聊天打招呼语，推荐联系方式';
            $form->html(Alert::make($info)->info());
            //                $form->textarea('job_description')->rows(4)->required();
            $form->textarea('greeting_message')->rows(3)->required();
            $form->radio('contact_genre', '联系方式推荐方案')->options(JobpositionModel::CONTACT_GENRE_LIST)->required()->default(JobpositionModel::CONTACT_GENRE_ORDER);
            $form->radio('contact_type')->options(JobpositionModel::CONTACT_TYPE_LIST)->required()
                ->when(JobpositionModel::CONTACT_MOBILE, function (Form $form) {
                    $form->hasMany('contactPhone', '手机号', function (Form\NestedForm $form) {
                        $formc = $form;
                        if ($formc->isEditing() && $formc->model()->cur_status < 3) {
                            $form->number('sort', '排序')->min(0)->help('数字越小越靠前');
                            $form->text('phone_number')->default('')->required();
                            $form->number('number', '最大报名数')->default('');
                            $form->text('recruit_num', '报名人数')->width(2)->disable();
                        } else {
                            $form->text('phone_number')->default('')->required();
                        }
                    })->useTable()->width(10);
                })->when(JobpositionModel::CONTACT_QQ, function (Form $form) {
                    $formc = $form;
                    $form->hasMany('contactQq', 'QQ', function (Form\NestedForm $form) use ($formc) {
                        if ($formc->isEditing() && $formc->model()->cur_status < 3) {
                            $form->number('sort', '排序')->min(0)->help('数字越小越靠前')->width(2);
                            $form->text('qq_number')->width(4);
                            $form->image('qq_qr_code')->uniqueName()->retainable()->autoUpload()->removable(false)->saveFullUrl()->default('')->width(4);
                            $form->number('number', '最大报名数')->default('')->width(2);
                            $form->text('recruit_num', '报名人数')->width(2)->disable();
                        } else {
                            $form->text('qq_number');
                            $form->image('qq_qr_code')->uniqueName()->autoUpload()->removable(false)->saveFullUrl()->default('');
                        }
                    })->useTable()->width(10);
                })->when(JobpositionModel::CONTACT_WECHAT, function (Form $form) {
                    $formc = $form;
                    $form->hasMany('contactWechat', '微信', function (Form\NestedForm $form) use ($formc) {
                        if ($formc->isEditing() && $formc->model()->cur_status < 3) {
                            $form->number('sort', '排序')->min(0)->help('数字越小越靠前')->width(2);
                            $form->text('wechat_number')->width(4);
                            $form->image('wechat_qr_code')->uniqueName()->retainable()->autoUpload()->removable(false)->saveFullUrl()->default('')->width(4);
                            $form->number('number', '最大报名数')->default('')->width(2);
                            $form->text('recruit_num', '报名人数')->width(2)->disable();
                        } else {
                            $form->text('wechat_number');
                            $form->image('wechat_qr_code')->uniqueName()->autoUpload()->removable(false)->saveFullUrl()->default('');
                        }
                    })->useTable()->width(10);
                })->when(JobpositionModel::CONTACT_DINGTALK, function (Form $form) {
                    $formc = $form;
                    $form->hasMany('contactDingtalk', '钉钉', function (Form\NestedForm $form) use ($formc) {
                        if ($formc->isEditing() && $formc->model()->cur_status < 3) {
                            $form->number('sort', '排序')->min(0)->help('数字越小越靠前')->width(2);
                            $form->text('dingtalk_number')->width(4);
                            $form->image('dingtalk_qr_code')->uniqueName()->retainable()->autoUpload()->removable(false)->saveFullUrl()->default('')->width(4);
                            $form->number('number', '最大报名数')->default('')->width(2);
                            $form->text('recruit_num', '报名人数')->width(2)->disable();
                        } else {
                            $form->text('dingtalk_number');
                            $form->image('dingtalk_qr_code')->uniqueName()->autoUpload()->removable(false)->saveFullUrl()->default('');
                        }
                    })->useTable()->width(10);
                });
            if ($form->isEditing() && $form->model()->cur_status == JobpositionModel::STATUS_AWAIT_REJECT) {
                $form->radio('is_check', '是否重新提交审核')->options([1 => '暂不提交', 2 => '提交审核'])->value(1);
            }
            $status = [JobpositionModel::STATUS_ON_LINE => '上架', JobpositionModel::STATUS_OFF_LINE => '下架'];
            if ($form->isEditing() && in_array($form->model()->cur_status, array_keys($status))) {
                $form->radio('cur_status', '状态')->options($status)->required();
            } else {
                $form->hidden('cur_status')->default(JobpositionModel::STATUS_CHECK_AWAIT);
            }
            $form->display('created_at');
            $form->display('updated_at');

            $form->saving(function (Form $form) {
                $distpicker_nationwide = $form->input('distpicker_nationwide');
                if ($distpicker_nationwide == 1) {
                    $form->region_province = '';
                    $form->region_city = '';
                    $form->region_region = '';
                }
                $contactPhone = $form->input('contactPhone');
                $contactQq = $form->input('contactQq');
                $contactWechat = $form->input('contactWechat');
                $contactDingtalk = $form->input('contactDingtalk');
                if ($form->input('contact_type') == JobpositionModel::CONTACT_MOBILE) {
                    if (!$contactPhone) {
                        return $form->response()->error('手机号不能为空~');
                    }
                    if (collect($contactPhone)->where('_remove_', 0)->count() == 0) {
                        return $form->response()->error('手机号不能为空~');
                    }
                }
                if ($form->input('contact_type') == JobpositionModel::CONTACT_QQ) {
                    if (!$contactQq) {
                        return $form->response()->error('QQ不能为空~');
                    }
                    if (collect($contactQq)->where('_remove_', 0)->count() == 0) {
                        return $form->response()->error('手机号不能为空~');
                    }
                }
                if ($form->input('contact_type') == JobpositionModel::CONTACT_WECHAT) {
                    if (!$contactWechat) {
                        return $form->response()->error('微信不能为空~');
                    }
                    if (collect($contactWechat)->where('_remove_', 0)->count() == 0) {
                        return $form->response()->error('微信不能为空~');
                    }
                }
                if ($form->input('contact_type') == JobpositionModel::CONTACT_DINGTALK) {
                    if (!$contactDingtalk) {
                        return $form->response()->error('钉钉不能为空~');
                    }
                    if (collect($contactDingtalk)->where('_remove_', 0)->count() == 0) {
                        return $form->response()->error('钉钉不能为空~');
                    }
                }

                $region_province = $form->input('region_province');
                $region_city = $form->input('region_city');
                $region_region = $form->input('region_region');
                if ($region_province || $region_city || $region_region) {
                    if (!$region_province || !$region_city || !$region_region) {
                        return $form->response()->error('请填写详细地址~');
                    }
                }

                if ($form->isEditing()) {
                    if ($form->input('is_check') == 2) {
                        $form->cur_status = JobpositionModel::STATUS_CHECK_AWAIT;
                    }
                    $form->deleteInput('is_check');
                    if (in_array($form->cur_status, [JobpositionModel::STATUS_ON_LINE, JobpositionModel::STATUS_OFF_LINE])) {
                        //        //修改后需要审核字段
                        $array = ['region_province', 'region_city', 'region_region', 'job_description', 'position_name', 'salary', 'salary_type', 'greeting_message'];
                        $model = $form->model();
                        $update = [];
                        foreach ($array as $item) {
                            if ($model->{$item} != $form->input($item)) {
                                $update[] = [
                                    'key' => $item,
                                    'old' => $model->{$item},
                                    'new' => $form->input($item)
                                ];
                            }
                            $form->deleteInput($item);
                        }
                        if ($update) {
                            JobPositionUpdateModel::query()->create([
                                'job_position_id' => $model->id,
                                'content' => $update,
                                'cur_status' => 1,
                            ]);
                        }
                    }
                }
                if (!$form->selection_date_start) {
                    $form->selection_date_start = null;
                }
                if (!$form->selection_date_end) {
                    $form->selection_date_end = null;
                }
                if (!$form->work_time_start) {
                    $form->work_time_start = null;
                }
                if (!$form->work_time_end) {
                    $form->work_time_end = null;
                } else {
                    $form->work_time_end = $form->work_time_end . ":59";
                }
            });
            $form->saved(function (Form $form,) {
                if (!auth('company')->user()->company_name) {
                    return $form->response()->success('请完善资料')->redirect('update-info');
                }
            });
            $form->disableViewButton();
            $form->disableDeleteButton();
            $form->disableEditingCheck();
            $form->disableViewCheck();
            $form->disableCreatingCheck();
        });
    }
}
